package com.cc.jdkjucdemo.CompletableFuture;

import java.util.concurrent.*;

/**
 * 一个是不带返回值，一个是带返回值
 */
public class CompletableFutureDemo01 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程start ......");
        String a = "123";
        // 没有返回结果，可以执行任务
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("子线程1开始执行：" + Thread.currentThread().getName() + a);
            System.out.println("子线程1执行中：" + Thread.currentThread().getName() + a);
            System.out.println("子线程1执行完成：" + Thread.currentThread().getName() + a);
        }, executor);

        // 没有返回结果，可以执行任务
        CompletableFuture<Void> future3 = CompletableFuture.runAsync(() -> {
            System.out.println("子线程1开始执行：" + Thread.currentThread().getName() + a);
            System.out.println("子线程1执行中：" + Thread.currentThread().getName() + a);
            System.out.println("子线程1执行完成：" + Thread.currentThread().getName() + a);
        }, executor);
        future1.get();

        // 带返回结果
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程2开始执行：" + Thread.currentThread().getName()+ a);
            System.out.println("子线程2执行中：" + Thread.currentThread().getName()+ a);
            int result = 10;
            System.out.println("子线程2执行完成，结果为：" + result + Thread.currentThread().getName()+ a);
            return result;
        }, executor);
        Integer result = future2.get();
        System.out.println("result = " + result);

        System.out.println("主线程end ......");
        executor.shutdown();
    }
}